<?php
/**
 * 路由类，解析 URL ，调用相应控制器与方法
 */
namespace phpless\core;

class Route
{
    protected static $instance;
    public $ctrl;
    public $action;
    private function __construct()
    {
        // dump('Route OK !!!');
        // 判断 URL_MODEL
        $url_model=config('URL_MODEL');
        $default_ctrl=config('DEFAULT_CTRL');
        $default_action=config('DEFAULT_ACTION');
        switch($url_model){
            case 0:
                $get=$_GET;
                $ctrl=isset($get['c'])?$get['c']:$default_ctrl;
                $action=isset($get['a'])?$get['a']:$default_action;
                $this->ctrl=$ctrl;
                $this->action=$action;
                break;
            case 1:
                $path_info=isset($_SERVER['PATH_INFO'])?$_SERVER['PATH_INFO']:0;
                $path_info=trim($path_info,'/');
                if(empty($path_info)){
                    $this->ctrl=$default_ctrl;
                    $this->action=$default_action;
                }else{
                    $path_arr=explode('/',$path_info);

                    $this->ctrl=$path_arr[0];
                    if(!isset($path_arr[1])){
                        $this->action=$default_action;
                    }else{
                        $this->action=$path_arr[1];
                    }
                    unset($path_arr[0]);
                    unset($path_arr[1]);
                    // 转化为URL参数
                    $count=count($path_arr);
                    for($i=2;$i<=$count;$i=$i+2){
                        $_GET[$path_arr[$i]]=$path_arr[$i+1];
                    }
                }
                break;
            default:
                throw new \Exception("请配置 URL_MODEL");
                break;
        }
    }
    // 单例模式获取Route类
    static function getInstance()
    {
        if(self::$instance){
            return self::$instance;
        }else{
            self::$instance=new Route();
            return self::$instance;
        }
    }
}
